import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.ToAnalysis;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

public class DocSearcher {
    public Index index = new Index();

    public DocSearcher() {
        index.load();
    }
    public List<Result> search(String query) {
        //1.对用户输入结果进行分词
        List<Term> terms = ToAnalysis.parse(query).getTerms();

        //2.通过用户输入的关键词在倒排索引中查询相关文档
        List<Relate> allDocs = new ArrayList<>();
        for(Term term : terms) {
            String key = term.getName();
            List<Relate> docs = index.getInverted(key);
            //判断是否有相关文章
            if(docs == null) {
                continue;
            }
            //添加到查询结果
            allDocs.addAll(docs);
        }

        //3.对查询到的结果按相关性降序排序
        allDocs.sort(new Comparator<Relate>() {
            @Override
            public int compare(Relate o1, Relate o2) {
                return o2.getWeight() - o1.getWeight();
            }
        });

        //4.通过正排索引查询文档相关信息并做返回处理
        List<Result> results = new ArrayList<>();
        for(Relate relate : allDocs) {
            DocInfo docInfo = index.getForward(relate.getDocId());
            Result result = new Result();
            result.setTitle(docInfo.getTitle());
            result.setUrl(docInfo.getUrl());
            result.setDesc(GenDesc(relate.getKey(), docInfo.getContent()));
            results.add(result);
        }
        return results;
    }

    private String GenDesc(String key, String content) {
        //通过关键词和正文生成摘要

        //在正文中查找第一次出现关键词的位置, 在关键词前后加空格保证单独匹配到该词
        //注意ansj分词结果会转为小写，所以需要把content也转为小写再匹配
        int firstPos = content.toLowerCase().indexOf(" " + key + " ");

        //取该位置前后各50个字符作为摘要
        int begPos = Math.max(firstPos - 50, 0);
        int endPos = Math.min(firstPos + 50, content.length());

        return content.substring(begPos, endPos);
    }
}
